//
//  ShopCheckViewController.swift
//  DSHCMerchant
//
//  Created by 罗德良 on 2018/5/5.
//  Copyright © 2018年 袋鼠好车. All rights reserved.
//

import UIKit
import Alamofire
class ShopCheckViewController: BaseViewController {

    @IBOutlet var businessLicenseImageView: UIImageView!
    
    @IBOutlet var nameTF: UITextField!
    
    @IBOutlet var idCardNumTF: UITextField!
    
    @IBOutlet var submitBtn: UIButton!
    
    var businessLicenseImageThumb = ""
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.view.backgroundColor = UIColor.white
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func chooseImageBtnPress(_ sender: UIButton) {
        alertChooseTakePhotoOrAlbum(typeName: "营业执照图片")
    }
    @IBAction func sumbitBtnPress(_ sender: UIButton) {
        
        if (self.nameTF.text == "") || (self.idCardNumTF.text == "" || businessLicenseImageThumb == ""){
            MBProgressHUD.alertShow(in: self.view, message: "请填写完整再提交", hidenAfter: 0.8, mode: MBProgressHUDMode.text)
            return
        }
        requestShopCheck(userName: nameTF.text!, cardNum: idCardNumTF.text!, businessId: businessLicenseImageThumb)
    }
    
    
    //选择照片或者拍照
    func alertChooseTakePhotoOrAlbum(typeName:String) -> Void {
        let alertController = UIAlertController(title: "上传图片", message: typeName,
                                                preferredStyle: .actionSheet)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let takephtotAction = UIAlertAction(title: "拍照", style: .default, handler:{
            action in
            let imagePicker = LDImagePicker.sharedInstance()
            imagePicker?.delegate = self as LDImagePickerDelegate
            imagePicker?.show(with: ImagePickerCamera, in: self, scale: 1)
        })
        let albumAction = UIAlertAction(title: "相册", style: .default, handler:{
            action in
            let imagePicker = LDImagePicker.sharedInstance()
            imagePicker?.delegate = self as LDImagePickerDelegate
            imagePicker?.show(with: ImagePickerPhoto, in: self, scale: 1)
            
        })
        alertController.addAction(cancelAction)
        alertController.addAction(takephtotAction)
        alertController.addAction(albumAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    //网络请求
    //提交认证
    func requestShopCheck(userName:String,cardNum:String,businessId:String) -> Void {
        Alamofire.request(uploadShopCheckInfoUrl, method:.post, parameters:["uid":UserModel.shareUser.data?.uid ?? String(),"username":userName,"card":cardNum,"thumb":businessId,"code":UserModel.shareUser.data?.recommend_code ?? String()])
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    var basemodel = BaseResponseOfModel<CommonModel>()
                    basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        //type 0等待审核  1通过审核
                        print("提交认证成功")
                        if basemodel.data?.type == "0"{
                            let checkStatusVC = CheckStatusViewController();
                            
                            checkStatusVC.title = "认证中"
                            checkStatusVC.checkStatus = "1"
                            self.navigationController?.pushViewController(checkStatusVC, animated: true)
                        }else {
                            let storeAddVC = StoreAddViewController();
                            
                            storeAddVC.title = "添加店铺"
                            self.navigationController?.pushViewController(storeAddVC, animated: true)
                        }
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
//                    MBProgressHUD.alertShow(in: self.view, message: "添加成功", hidenAfter: 0.8, mode: MBProgressHUDMode.text)
//                    self.navigationController?.popViewController(animated: true)
                case false:
                    print(response.result.error!)
                }
        }        
    }
    
    //上传单张封面图片
    func requestUploadCoverPhoto(imageName:String,imageData:Data) -> Void {
        
        Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(imageData, withName: "file", fileName:imageName, mimeType: "image/jpeg")
        }, to: uploadQiuPhotoUrl) { (encodingResult) in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseString { response in
                    
                    switch response.result.isSuccess {
                    case true:
                        var basemodel = BaseResponseOfModel<PhotoModel>()
                        basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                        switch basemodel.status! {
                        case true:
                            print("上传成功")
                            if (basemodel.data?.thumb)! != "" {                                self.businessLicenseImageThumb = (basemodel.data?.thumb)!
                            }
                            
                        case false:
                             MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                        }
                    case false:
                        print(response.result.error!)
                    }
                }
            case .failure(let encodingError):
                print(encodingError)
            }
        }
    }
    
    //上传多张展示图片
//    func requestUploadCoverPhotos(imageName:String,imageData:Data) -> Void {
//
//        Alamofire.upload(multipartFormData: { multipartFormData in
//            multipartFormData.append(imageData, withName: "Filedata", fileName:imageName, mimeType: "image/jpeg")
//        }, to: uploadQiuPhotosUrl) { (encodingResult) in
//            switch encodingResult {
//            case .success(let upload, _, _):
//                upload.responseString { response in
//
//                    switch response.result.isSuccess {
//                    case true:
//                     print("fff")
//
////                        var basemodel = BaseResponseOfModel<PhotoModel>()
////                        basemodel = BaseResponseOfModel.deserialize(from: response.value)!
////                        switch basemodel.status! {
////                        case true:
////                            if (self.footerView?.imageArray.count)! > 0 {
////                                if(self.footerView?.imageArray.count)! == self.showImageIndex! {
////                                    print("点击的最后一个")
////                                    if self.footerView?.imageArray.count != 5{//添加
////                                        self.addImageArrayEvents(model: basemodel.data!)
////                                    }else {//由于是最后一个 替换
////                                        self.replaceImageArrayEvents(model: basemodel.data!)
////                                    }
////                                }else {//替换
////                                    print("其他的")
////                                    self.replaceImageArrayEvents(model: basemodel.data!)
////                                }
////                            } else {//第一个+
////                                //添加到图片数组里面
////                                self.addImageArrayEvents(model:basemodel.data!)
////
////                            }
////                            print("上传成功")
////                        case false:
////                            print("数据错误")
////                        }
////                    case false:
////                        print(response.result.error!)
////                    }
////                }
//            case .failure(let encodingError):
//                print(encodingError)
//            }
//        }
//    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension ShopCheckViewController: LDImagePickerDelegate {
    
    func imagePickerDidCancel(_ imagePicker: LDImagePicker!) {
        
    }
    func imagePicker(_ imagePicker: LDImagePicker!, didFinished editedImage: UIImage!) {
        let imageData = UIImageJPEGRepresentation(editedImage, 0.00001)
        let formatter = DateFormatter.init()
        formatter.dateFormat = "yyyyMMddHHmmss"
        let str = formatter.string(from:NSDate() as Date) + ".jpg"
        self.businessLicenseImageView.image = editedImage
        requestUploadCoverPhoto(imageName:str, imageData:imageData!)
    }
}

